<script setup>
import DetailHeader from '@/components/DetailHeader.vue'
import { userOneArticleService } from '@/api/article/index.js'
import { onMounted, ref, computed, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import NavBar from '@/components/NavBar.vue'
import { showImagePreview } from 'vant'
const route = useRoute()
const articleDetail = ref()

onMounted(async () => {
  try {
    const response = await userOneArticleService(route.query.id)
    // console.log(response)
    articleDetail.value = response.data.data
    console.log(articleDetail.value)
  } catch (error) {
    console.error('Failed to fetch article:', error)
  }
})

//原因：v-html 会直接渲染 HTML 内容，但是它不会处理绑定的 Vue 事件。

watch(articleDetail, async () => {
  // 在 articleDetail 更新后，手动绑定点击事件
  await nextTick(() => {
    // 获取所有 <img> 标签并绑定事件
    const images = document.querySelectorAll('.article-content img')
    images.forEach((img) => {
      img.addEventListener('click', (event) => {
        // 获取图片的 src 并触发预览
        showImagePreview([event.target.src])
      })
    })
  })
})
// 定义一个方法来处理 attachment.url
const getCleanUrl = (url) => {
  if (!url) return ''
  const urlObj = new URL(url)
  return urlObj.pathname + urlObj.search + urlObj.hash
}

// 定义一个计算属性来处理每个附件的 URL
const cleanUrls = computed(() => {
  if (!articleDetail.value || !articleDetail.value.attachmentList) return []
  return articleDetail.value.attachmentList.map((attachment) => ({
    ...attachment,
    cleanUrl: getCleanUrl(attachment.url)
  }))
})

// 定义计算属性以去除内容中的域名和端口
const cleanedContent = computed(() => {
  if (
    !articleDetail.value ||
    !articleDetail.value.articleListDTO ||
    !articleDetail.value.articleListDTO.article
  ) {
    return ''
  }

  let content = articleDetail.value.articleListDTO.article.content

  // 为没有 width 属性的 <img> 标签添加 width="100%"
  //这里的replace并不是真的替代，而是返回一个新的结果
  content = content.replace(/<img(?!.*width=)[^>]*>/g, (imgTag) => {
    const newImgTag = imgTag.replace('<img', '<img width="100%"')
    console.log(newImgTag) // 打印修改后的标签（可选，用于调试）
    return newImgTag
  })

  // 移除特定的 URL 前缀
  content = content.replace(/http:\/\/134\.107\.67\.26:8088/g, '')

  content = content.replace(
    /<img([^>]*?)src="([^"]+)"([^>]*?)>/g,
    (match, beforeSrc, src, afterSrc) => {
      // 在原来的标签中插入 @click="showImagePreview([src])"

      return `<img @click="showImagePreview(['${src}'])" ${beforeSrc}src="${src}"${afterSrc}>`
    }
  )
  console.log(content)
  return content
})
</script>
<template>
  <div class="container">
    <NavBar name="课件详情"></NavBar>
    <!-- articleListDTO不包括附件数据 -->
    <DetailHeader
      v-if="articleDetail"
      :object="articleDetail.articleListDTO"
      type="课件"
    ></DetailHeader>
    <article v-if="articleDetail" class="article-content" v-html="cleanedContent"></article>

    <article
      class="document-article"
      v-if="articleDetail && articleDetail.attachmentList.length > 0"
    >
      <h2 @click="console.log(cleanedContent)">附件列表</h2>
      <ul>
        <li v-for="attachment in cleanUrls" :key="attachment.id">
          <a :href="attachment.cleanUrl">
            <van-icon name="description-o" class="icon-margin" />{{ attachment.name }}
          </a>
          <!-- <div>{{ attachment.cleanUrl }}</div> -->
        </li>
      </ul>
    </article>
  </div>
</template>
<style scoped>
.container {
  max-width: 100vw;
}
.article-content {
  max-width: 100%;

  line-height: 2; /* 默认的 prose 行高 */
  font-size: 1rem; /* 默认的 prose 字体大小 */
  color: #333; /* 默认的 prose 文字颜色 */
  margin: 1.5rem;

  overflow-wrap: break-word; /* 自动换行处理长单词或URL */
  word-wrap: break-word;
  word-break: break-all; /* 强制对超长URL进行换行 */
  white-space: normal; /* 确保内容正常换行 */
}

.document-article {
  margin-top: 1.5rem; /* 相当于 mt-6 */
  margin-bottom: 2rem;
  margin-left: 0.5rem;
  margin-right: 0.5rem;
}

.document-article h2 {
  font-size: 1.5rem; /* 默认的 h2 大小 */
  margin-bottom: 1rem; /* 添加一些底部间距 */
}

.document-article ul {
  list-style-type: none; /* 移除默认的列表样式 */
  padding: 0; /* 移除默认的内边距 */
  margin: 0; /* 移除默认的外边距 */
}

.document-article li {
  margin-bottom: 0.5rem; /* 每个列表项之间的间距 */
}

.document-article a {
  color: #333; /* 链接颜色 */
  text-decoration: none; /* 移除下划线 */
  display: flex; /* 使内容在一行显示 */
  align-items: center; /* 垂直居中对齐 */
}

.document-article a:hover {
  text-decoration: underline; /* 鼠标悬停时显示下划线 */
}

.icon-margin {
  margin-right: 0.5rem; /* 相当于 mr-2 */
}
</style>
